package my.jwds.p21;


import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ListNode {
     public int val;
     public ListNode next;
     public ListNode() {}
     public ListNode(int val) { this.val = val; }
     public ListNode(int val, ListNode next) { this.val = val; this.next = next;}

     @Override
     public String toString() {
         List result = new ArrayList();
         Set<ListNode> nodes = new HashSet<>();
         result.add(val);
         nodes.add(this);
         ListNode node = next;
         while(node != null){
             if (nodes.contains(node)){
                 return result+"环";
             }
             nodes.add(node);
             result.add(node.val);
             node = node.next;
         }
         return result.toString();
     }

     public static ListNode to(int [] o){
         if (o.length == 0)return new ListNode();
         ListNode temp = new ListNode();
         ListNode result = temp;
         for (int i : o) {
             temp.next = new ListNode(i);
             temp = temp.next;
         }
         return result.next;
     }
 }
